/**
 * 租户费用相关功能
 */
import { mysql } from 'src-ssr/db/connect';
import TableHelper from 'src-ssr/db/tableHelper';
import * as tools from 'src-ssr/util/common';
import logs from 'src-ssr/util/logs';
import { Sequelize, Op, QueryTypes } from 'sequelize';
import models, { sequelize } from 'src-ssr/db/sequelize';
import moment from 'moment';
import shortid from 'shortid';
import md5 from 'md5';

import * as singleUtils from 'src-ssr/controller/common/singleOperate';

import listConfig from 'app/search/manager/payment/list.js';

const menuName = 'payment';
const modelName = 'm_tenant_fees';
const modelLabel = '缴费记录';

// 列表
export const list = async (req, res) => {
  const { startRow, count, filter, sortBy, descending } = req.body;

  const where = await tools.assemblyWhere({
    filter,
    searchConfig: listConfig.search,
    fn: ({ where, field, search }) => {
      if (field === 'expire') {
        if (search === 'yes') {
          where.expire_time = { [Op.lt]: moment().unix() }
        } else {
          where.expire_time = { [Op.gt]: moment().unix() }
        }
      }
    }
  });
  where.id = { [Op.gt]: 0 }; // 取id大于0的租户

  const exclude = ['create_user_id', 'modify_user_id', 'history', 'uid'];
  // 只取单条数据
  if (filter && filter.id) {
    where.id = filter.id;
    exclude.splice(exclude.indexOf('history'), 1);
  }

  const order = sortBy ? [[sortBy, descending ? 'DESC' : 'ASC']] : [];

  const user = await tools.getLoginUser(req.get('Authorization').split(' ')[1]);
  const right = await tools.checkUserRight(user, menuName, ['data']);
  if (!right.data) { // 是否有查看全部的权限
    where.create_user_id = user.id;
  }

  let ret = { rows: [], count: 0 };
  try {
    ret = await models[modelName].findAndCountAll({
      attributes: { exclude },
      include: [{
        model: models.m_tenants,
        attributes: ['tenant_name']
      }],
      where,
      order,
      offset: count ? startRow : undefined,
      limit: count || undefined,
      group: count ? `${modelName}.id` : undefined
    });
  } catch (e) {
    console.error(modelLabel + '列表出错', e);
  }

  // 处理其它数据
  const rows = [];
  ret.rows.forEach(row => {
    const jsonRow = row.toJSON();

    tools.flatDetail(['m_tenant'], jsonRow); // 拉平信息
    jsonRow._owner = row.create_user_id == user.id; // 是否为拥有者
    rows.push(jsonRow);
  });

  if (filter && filter.id) {
    return rows.length > 0 ? rows[0] : {};
  } else {
    res.json({
      data: rows,
      rowsNumber: typeof ret.count === 'object' ? ret.count.length : ret.count
    });
  }
};

// 详细信息
export const detail = async (req, res) => {
  req.body.filter = { id: req.body.id };

  const ret = await list(req);

  res.json(ret);
};

/**
 * 新增
 */
export const create = async (req, res) => {
  const { formData } = req.body;
  const ret = await singleUtils.createData(modelName, modelLabel, menuName, req);

  // 更新有效期
  await models.m_tenants.update({
    expire_time: formData.expire_time
  }, {
    where: {
      id: formData.tenant_id
    }
  });

  res.json(ret);
};

/**
 * 更新
 */
// export const update = async (req, res) => {
//   const ret = await singleUtils.updateData(modelName, modelLabel, menuName, req);
//   res.json(ret);
// };

/**
 * 删除
 */
// export const destroy = async (req, res) => {
//   const ret = await singleUtils.destroyData(modelName, modelLabel, menuName, req);
//   res.json(ret);
// };

/**
 * 获取租户有效期开始时间
 */
export const getTenantStart = async (req, res) => {
  const { tenant_id } = req.body;
  const tenant = await models.m_tenants.findOne({
    attributes: ['expire_time'],
    where: { id: tenant_id }
  });

  // 已过期从当天开始算
  let beginTime = moment().startOf('day').unix();

  // 未过期的从有效期结束日的后一天开始算
  if (tenant && tenant.expire_time > moment().unix()) {
    beginTime = moment(tenant.expire_time, 'X').add(1, 'days').startOf('day').unix();
  }
  res.json({
    start: beginTime
  });
};
